<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\api\model\ding;

use app\api\model\ding\ClerkMember as ClerkMemberModel;
use app\api\model\ding\OrderContent as OrderContentModel;
use app\api\model\ding\OrderLog as OrderLogModel;
use app\api\model\ding\OrderSeat as OrderSeatModel;
use app\api\model\wxapp\Setting as WxappSettingModel;
use app\api\service\ding\order\PaySuccess as OrderPaySuccesService;
use app\api\service\Message as MessageWechatService;
use app\api\service\Payment as PaymentService;
use app\api\service\User as UserService;
use app\common\enum\ding\OrderType as OrderTypeEnum;
use app\common\enum\ding\Ribao as SceneEnum;
use app\common\enum\order\PayType as OrderPayTypeEnum;
use app\common\library\wechat\Link;
use app\common\model\ding\Order as OrderModel;
use app\common\model\ding\Ribao as RibaoModel;
use app\common\service\Day as DayService;
use app\common\service\message\ding\Order as OrderSendService;
use app\common\service\Order as OrderService;
use app\store\service\wxapp\Message as MessageService;
use cores\exception\BaseException;
use think\facade\Db;

/**
 * 商品评价模型
 * Class Article
 * @package app\api\model
 */
class Order extends OrderModel
{
    /**
     * 隐藏字段
     * @var array
     */
    protected $hidden = [
        'is_delete',
        'store_id',

        'update_time',
    ];
    /**
     * 待支付订单详情
     * @param string $orderNo 订单号
     * @return null|static
     */
    public static function getPayDetail(string $orderNo): ?Order
    {

        return self::detail(['order_no' => $orderNo, 'pay_status' => 10, 'is_delete' => 0], ['user']);
    }

    /**
     * 获取文章详情并累计阅读次数
     * @param int $articleId 文章ID
     * @return static|null
     * @throws BaseException
     */
    public static function getDetail(int $orderId, int $isUser = 0)
    {
        // 获取文章详情
        $detail = parent::detail($orderId, ['content.image', 'letters.image', 'clerk.role', 'seats']);
        if (empty($detail) || $detail['is_delete']) {
            throwError('很抱歉，当前预订不存在');
        }
        if ($isUser == 1 && $detail['user_id'] == 0) {
            $userId = UserService::getCurrentLoginUserId();
            $detail->save(['user_id' => $userId]);
        }

        return $detail;
    }
    //用户取消预订

    public function cancelUser($type = '')
    {

        //日报

        $this->save(['order_status' => 30, 'reason' => $type]);

        $clerks = Db::name('store_shop_clerk')->where('shop_id', $this['shop_id'])->where('cancel_msg', 1)
            ->select()->toArray();

        $shopName = Db::name('store_shop')->where('shop_id', $clerks[0]['shop_id'])->value('shop_name');
        foreach ($clerks as $key => $value) {
            $opend_id = $value['oauth_id'];
            if ($opend_id) {
                // 执行发送
                $MessageService         = new MessageService;
                $content['template_id'] = 'dJbZJBmRkcBmgkH6vql0e16uMvzXmzXxl3tsiM9Zuis';
                $content['page']        = '';

                $content['data']['thing1'] = $shopName;
                $content['data']['thing2'] = $this['name'];
                $content['data']['time4']  = $this['date'] . ' ' . $this['time'];
                $content['data']['thing3'] = $this['real_name'];
                //暂时注释
                $MessageService->send($opend_id, $content);
            }
        }

        return true;
    }

    public function cancel()
    {

        $this->save(['status' => 30, 'order_status' => 30]);

        Db::name('ding_order_seat')->where('order_id', $this['id'])->update(['status' => 30]);

        //操作日记
        $user  = UserService::getCurrentLoginUser(true);
        $clerk = Db::name('store_shop_clerk')->where('shop_id', $this['shop_id'])->where('user_id', $user['user_id'])
            ->find();
        $log['content']  = '取消了该订单';
        $log['status']   = OrderTypeEnum::CANCEL;
        $log['order_id'] = $this['id'];
        $log['clerk_id'] = $clerk['clerk_id'];
        $log['shop_id']  = $clerk['shop_id'];

        OrderLogModel::increased($log);

        $clerks = Db::name('store_shop_clerk')->where('shop_id', $clerk['shop_id'])->where('cancel_msg', 1)
            ->select()->toArray();
        $shopName = Db::name('store_shop')->where('shop_id', $clerk['shop_id'])->value('shop_name');
        foreach ($clerks as $key => $value) {
            $opend_id = $value['oauth_id'];
            if ($opend_id) {
                // 执行发送
                $MessageService            = new MessageService;
                $content['template_id']    = 'dJbZJBmRkcBmgkH6vql0e16uMvzXmzXxl3tsiM9Zuis';
                $content['page']           = '';
                $content['data']['thing1'] = $shopName;
                $content['data']['thing2'] = $this['name'];
                $content['data']['time4']  = $this['date'] . ' ' . $this['time'];
                $content['data']['thing3'] = $clerk['real_name'];
                //暂时注释
                $MessageService->send($opend_id, $content);
            }
        }

        return true;
    }
    //确认客到
    public function queu()
    {

        $this->save(['status' => 20]);
        Db::name('ding_order_seat')->where('order_id', $this['id'])->update(['status' => 20]);

        //日报
        $ribao['shop_id']  = $this['shop_id'];
        $ribao['clerk_id'] = $this['clerk_id'];

        RibaoModel::add(SceneEnum::YXDD, $ribao, '确认客到，订单号：' . $this['order_no']);

        //操作日记
        $user  = UserService::getCurrentLoginUser(true);
        $clerk = Db::name('store_shop_clerk')->where('shop_id', $this['shop_id'])->where('user_id', $user['user_id'])
            ->field('clerk_id,shop_id,user_id')->find();
        $log['content']  = '确认客到';
        $log['status']   = OrderTypeEnum::REACH;
        $log['order_id'] = $this['id'];
        $log['clerk_id'] = $clerk['clerk_id'];
        $log['shop_id']  = $clerk['shop_id'];
        OrderLogModel::increased($log);

        $clerks = Db::name('store_shop_clerk')->where('shop_id', $this['shop_id'])
            ->where('reach_msg', 1)->select()->toArray();

        foreach ($clerks as $key => $value) {
            $opend_id = $value['oauth_id'];
            if ($opend_id) {
                // 执行发送
                $MessageService         = new MessageService;
                $content['template_id'] = 'sRfV39ZLiAF7urTFM63GpnWfaVgNaXzprgeIgd-_U1M';
                $content['page']        = 'pagesNew/order/detail?orderId=' . $this['id'] . '&shopId=' . $clerk['shop_id'];

                $shop                      = Db::name('store_shop')->where('shop_id', $clerk['shop_id'])->field('shop_name,address')->find();
                $content['data']['thing1'] = $shop['shop_name'];
                $content['data']['thing2'] = $shop['address'];
                $content['data']['time4']  = $this['date'] . ' ' . $this['time'];
                $content['data']['thing6'] = $this['name'];

                $MessageService->send($opend_id, $content);
            }
        }

        return true;
    }
    //调整餐位
    public function change($data)
    {
        $user  = UserService::getCurrentLoginUser(true);
        $clerk = Db::name('store_shop_clerk')->where('shop_id', $this['shop_id'])->where('user_id', $user['user_id'])
            ->field('clerk_id,shop_id,user_id')->find();
        return $this->transaction(function () use ($clerk, $data) {
            $c = new DayService();

            $date_arr = explode('-', $data['date']);

            $data['week'] = $c->get_week_day($data['date']);

            $today              = $c->convertSolarToLunar($date_arr[0], $date_arr[1], $date_arr[2]);
            $data['lunar_date'] = $today[1] . $today[2];
            $old_seat           = Db::name('ding_seat')->where('seat_id', $data['old_seat_id'])->value('name');
            $new_seat           = Db::name('ding_seat')->where('seat_id', $data['new_seat_id'])->value('name');
            $data['name']       = $new_seat;
            if ($data['type'] == '午餐' || $data['type'] == '晚餐') {
                $data['type'] = $data['type'] == '午餐' ? 1 : 2;
            }

            Db::name('ding_order_seat')
                ->where('order_id', $this['id'])
                ->where('seat_id', $data['old_seat_id'])
                ->update([
                    'seat_id' => $data['new_seat_id'],
                    'name'    => $new_seat,
                    'week'    => $data['week'], 'lunar_date' => $data['lunar_date'], 'type' => $data['type']]);

            //操作日记

            $log['content']  = '将订单从 ' . $old_seat . ' 餐位转到了' . $new_seat . ' 餐位';
            $log['status']   = OrderTypeEnum::CHANGE;
            $log['order_id'] = $this['id'];
            $log['clerk_id'] = $clerk['clerk_id'];
            $log['shop_id']  = $clerk['shop_id'];

            OrderLogModel::increased($log);

            $this->save($data);

            $clerks = Db::name('store_shop_clerk')->where('shop_id', $clerk['shop_id'])->where('change_msg', 1)->select()->toArray();

            foreach ($clerks as $key => $value) {
                $opend_id = $value['oauth_id'];
                if ($opend_id) {

                    // 执行发送

                    $MessageService         = new MessageService;
                    $content['template_id'] = 'pnmFVojVvw8qC0gFAT71MR0IlPs6r8KDxE85VeoFozY';
                    $content['page']        = 'pagesNew/order/detail?orderId=' . $this['id'] . '&shopId=' . $clerk['shop_id'];

                    $content['data']['character_string1'] = $this['real_name'];
                    $content['data']['const2']            = $log['content'];
                    $content['data']['const3']            = $data['week'];
                    $content['data']['time4']             = $data['lunar_date'];

                    $result = $MessageService->send($opend_id, $content);
                }
            }

            return true;

        });

    }
    //店员确认菜单

    public function caidanQueu($data)
    {

        $goods       = $data['cartList'];
        $total_price = 0;
        if (count($goods) == 0) {
            Db::name('ding_order_food')->where('order_id', $this['id'])->where('status', 0)->delete();
            Db::name('ding_order_menu')->where('order_id', $this['id'])->where('status', 0)->delete();

        } else {
            $ids      = array_column($goods, 'order_food_id');
            $ids_menu = array_column($goods, 'menu_id');
            Db::name('ding_order_food')
                ->where('order_id', $this['id'])
                ->where('order_food_id', 'not in', $ids)
                ->where('status', 0)->delete();

            Db::name('ding_order_menu')
                ->where('order_id', $this['id'])
                ->where('menu_id', 'not in', $ids_menu)
                ->where('status', 0)->delete();

            Db::name('ding_order_menu')
                ->where('order_id', $this['id'])
                ->where('menu_id', 'in', $ids_menu)
                ->update(['status' => 1, 'total_num' => 0, 'total_price' => 0]);
            $menu = [];

            foreach ($goods as $key => $value) {
                $menu1['menu_id']     = $value['menu_id'];
                $menu1['total_num']   = $value['total_num'];
                $menu1['total_price'] = $value['total_price'];

                $menu[] = $menu1;

                Db::name('ding_order_food')->where('order_food_id', $value['order_food_id'])
                    ->update(['status' => 1, 'total_num' => $value['total_num'], 'total_price' => $value['total_num'] * $value['price'], 'total_pay_price' => $value['total_num'] * $value['price']]);
                $total_price += $value['total_num'] * $value['price'];

            }

            if (count($menu) > 0) {
                foreach ($menu as $key => $value) {

                    Db::name('ding_order_menu')->where('menu_id', $value['menu_id'])->inc('total_num', (int) $value['total_num'])->update();
                    Db::name('ding_order_menu')->where('menu_id', $value['menu_id'])
                        ->inc('total_price', (int) $total_price)->update();

                }
            }

        }

        return true;
    }

    //用户确认菜单
    public function updateOrder($data)
    {

        return $this->transaction(function () use ($data) {
            $data['pay_price']   = 0;
            $data['total_price'] = 0;
            $this->save($data);

            return true;
        });
    }
    public function edit($data)
    {

        return $this->transaction(function () use ($data) {

            $this->save($data);
            $data['order_id']   = $this['id'];
            $data['type']       = $this['type'];
            $data['lunar_date'] = $this['lunar_date'];
            $data['week']       = $this['week'];
            $data['shop_id']    = $this['shop_id'];
            if (! empty($data['seatList'])) {
                OrderSeatModel::increased($data);
            } else {
                $model = OrderSeatModel::getDetail(['order_id' => $this['id']]);

                $model->edit($data);
            }

            Db::name('ding_order_content')->where('order_id', $this['id'])->delete();
            if (isset($data['contentList'])) {
                // 内容
                OrderContentModel::increased((int) $this['id'], $data['contentList']);
            }

            //操作日记
            $user  = UserService::getCurrentLoginUser(true);
            $clerk = Db::name('store_shop_clerk')->where('user_id', $user['user_id'])
                ->field('clerk_id,shop_id')->find();
            $log['content']  = '编辑订单';
            $log['status']   = OrderTypeEnum::EDIT;
            $log['order_id'] = $this['id'];
            $log['clerk_id'] = $clerk['clerk_id'];
            $log['shop_id']  = $clerk['shop_id'];
            OrderLogModel::increased($log);

            return true;
        });
    }

    //用户预订
    public function userAdd(array $data)
    {
        // 当前用户信息
        $user = UserService::getCurrentLoginUser(true);

        $order = Db::name('ding_order_seat')
            ->where('type', $data['type'])
            ->where('date', $data['date'])
            ->where('seat_id', $data['seat_id'])

            ->where('status', '<', 30)->find();

        //判断是否被预订
        if ($order) {
            throwError('该日期已被预订，请更换其他包厢或日期');
            return false;
        }

        //占座
        $lock = Db::name('ding_seat_lock')->where('shop_id', $data['shop_id'])
            ->where('seat_id', $data['seat_id'])
            ->where('date', $data['date'])
            ->where('type', $data['type'])
            ->find();
        if ($lock) {
            throwError('该日期已被占座');

            return false;
        }

        // 添加
        return $this->transaction(function () use ($user, $data) {

            $c = new DayService();

            $date_arr = explode('-', $data['date']);

            $data['week']      = $data['week'];
            $data['real_name'] = $user['nick_name'];
            $data['mobile']    = $user['mobile'];
            $data['clerk_id']  = $data['clerk_id'];
            $data['order_no']  = OrderService::createOrderNo();

            $today              = $c->convertSolarToLunar($date_arr[0], $date_arr[1], $date_arr[2]);
            $data['lunar_date'] = $today[1] . $today[2];

            $data = array_merge($data, ['user_id' => $user['user_id'],
                'store_id'                            => self::$storeId]);
            $shopId = $data['shop_id'];
            $shop   = Db::name('store_shop')->where('shop_id', $shopId)->find();

            $data['seat_money'] = $shop['seat_money'];

            $this->save($data);

            // $clerkMember = new ClerkMemberModel;
            // $clerkMember->add($data);

            //餐位
            $data['order_id'] = $this['id'];

            OrderSeatModel::increased($data);

            $clerks = Db::name('store_shop_clerk')->where('shop_id', $shopId)
                ->group('user_id')
                ->where('reserve_msg', 1)

                ->select()->toArray();

            foreach ($clerks as $key => $value) {
                $opend_id = $value['oauth_id'];
                if ($opend_id) {
                    // 执行发送

                    $MessageService         = new MessageService;
                    $content['template_id'] = 'f_-0dcAA9sSC4KM1JzMgwgoyaljyxe3yrnig7wN8sNQ';
                    $content['page']        = 'pagesNew/help/add?id=' . $data['order_id'];

                    $content['data']['time4'] = Date('Y-m-d H:i');
                    //$content['data']['phrase9'] = $data['real_name'];
                    $content['data']['phone_number14'] = $data['mobile'];
                    $content['data']['time16']         = $data['date'] . ' ' . $data['time'];
                    $content['data']['thing3']         = '订厢';

                    //暂时注释
                    $MessageService->send($opend_id, $content);

                }
            }

            return $data['order_id'];
        });
    }
    /*
	*安排落座
	*/
    public function add_queu($type, array $data)
    {

        //占座
        $lock = Db::name('ding_seat_lock')->where('shop_id', $data['shop_id'])
            ->where('seat_id', $data['seat_id'])
            ->where('date', $data['date'])
            ->where('type', $data['type'])
            ->find();
        if ($lock) {
            throwError('该日期已被占座');
            return false;
        }

        // 当前用户信息
        $user  = UserService::getCurrentLoginUser(true);
        $clerk = Db::name('store_shop_clerk')->where('shop_id', $this['shop_id'])
            ->where('user_id', $user['user_id'])
            ->find();

        // 添加
        return $this->transaction(function () use ($clerk, $data, $type) {

            if (isset($data['seatList'])) {

            }

            $c = new DayService();

            $date_arr = explode('-', $data['date']);

            $data['week'] = $c->get_week_day($data['date']);

            $today              = $c->convertSolarToLunar($date_arr[0], $date_arr[1], $date_arr[2]);
            $data['lunar_date'] = $today[1] . $today[2];

            $data = array_merge($data, ['clerk_id' => $clerk['clerk_id'], 'shop_id' => $clerk['shop_id'],
                'store_id'                             => self::$storeId]);

            $data['order_status'] = 10; //确认成功
                                        //$data['pay_status'] = 10; //待支付

            $data['name']        = $data['seatList'][0]['name']; //待支付
            $data['pay_price']   = $this['seat_money'];
            $data['total_price'] = $this['seat_money'];

            $this->save($data);
            if (isset($data['contentList'])) {
                // 内容
                OrderContentModel::increased((int) $this['id'], $data['contentList']);
            }
            if (! empty($data['mobile'])) {
                $clerkMember = new ClerkMemberModel;
                $clerkMember->add($data);
            }
            //餐位
            $data['order_id'] = $this['id'];
            $data['type']     = $this['type']; //午餐，晚餐

            OrderSeatModel::increased($data);

            if (! empty($data['mobile'])) {
                $clerkMember = new ClerkMemberModel;
                $clerkMember->add($data);
            }
            //更新用于预定次数
            Db::name('ding_clerk_member')->where('mobile', $data['mobile'])
                ->where('shop_id', $data['shop_id'])->inc('times', 1)->update();

            //操作日记
            $log['content']  = '确认了此订单';
            $log['status']   = OrderTypeEnum::CREATE;
            $log['order_id'] = $this['id'];
            $log['clerk_id'] = $clerk['clerk_id'];
            $log['shop_id']  = $clerk['shop_id'];

            OrderLogModel::increased($log);

            $orderId = $this['id'];
            $shopId  = $this['shop_id'];
            $shop    = Db::name('store_shop')->where('shop_id', $shopId)->find();
            $clerks  = Db::name('store_shop_clerk')->where('shop_id', $this['shop_id'])
                ->group('user_id')
                ->where('reserve_msg', 1)->select()->toArray();

            foreach ($clerks as $key => $value) {
                $opend_id = $value['oauth_id'];
                if ($opend_id) {
                    // 执行发送

                    $MessageService         = new MessageService;
                    $content['template_id'] = 'yWrzJ1FuLCamRw_Rm55kwvtylWYD0JGys1U7g4_fMmk';
                    $content['page']        = 'pagesNew/order/detail?orderId=' . $orderId . '&shopId=' . $shopId;

                    $content['data']['thing4']            = $shop['shop_name'];
                    $content['data']['time3']             = $this['date'] . ' ' . $this['time'];
                    $content['data']['character_string5'] = $this['order_no'];
                    $content['data']['thing6']            = $data['name'];
                    $content['data']['const1']            = '订座成功';
                    $content['data']['time4']             = $this['date'] . ' ' . $this['time'];

                    //暂时注释
                    $MessageService->send($opend_id, $content);

                }
            }

            //发送短信
            if ($type == 1) {
                $messageService = new OrderSendService(self::$storeId);
                $sex            = '先生/女士';
                if ($data['sex'] == 1) {
                    $sex = '先生';
                } elseif ($data['sex'] == 2) {
                    $sex = '女士';
                }
                // 获取当前小程序信息
                $config = self::getMpWxConfig();
                // 微信登录 (获取session_key)
                $WxUser = new Link($config['app_id'], $config['app_secret']);

                $param['path']  = 'pagesNew/order/detail';
                $param['query'] = 'orderId=' . $this['id'] . '&shopId=' . $clerk['shop_id'];

                $result = $WxUser->getLinkLong($param);
                $url    = $result['url_link'];

                $date          = $data['date'] . ' ' . $data['time'];
                $send['users'] = [['real_name' => $data['real_name'] . $sex, 'mobile' => $data['mobile'],
                    'date'                         => $date, 'seat_name'                  => $data['name'], 'page' => $url]];
                $send['clerk'] = $clerk;
                $send['shop']  = $shop;

                $messageService->send($send);

            }

            //发送订阅通知给小程序用户

            $MessageService = new MessageWechatService;

            $params   = [];
            $opend_id = Db::name('user_oauth')->where('user_id', $this['user_id'])->value('oauth_id');

            $params['template_id'] = 'Ua_7E9w8LLsG7063moXLuOgouPbUg6piUEASEmuhvwM';
            $params['page']        = 'pagesNew/user/order/detail?orderId=' . $this['id'] . '&shopId=' . $this['shop_id'];
            $params['data']        = [
                'thing1' => ['value' => $shop['shop_name']],
                'thing2' => ['value' => $shop['address']],
                'time3'  => ['value' => $this['date'] . ' ' . $this['time']],
                'thing4' => ['value' => $this['name']],
            ];

            $MessageService->send($opend_id, $params);

            return $this['id'];
        });
    }

    public function add(int $type, array $data)
    {

        //占座
        $lock = Db::name('ding_seat_lock')->where('shop_id', $data['shop_id'])
            ->where('seat_id', $data['seat_id'])
            ->where('date', $data['date'])
            ->where('type', $data['type'])
            ->find();
        if ($lock) {
            throwError('该日期已被预订，请更换其他包厢或日期');
            return false;
        }

        // 当前用户信息
        $user  = UserService::getCurrentLoginUser(true);
        $clerk = Db::name('store_shop_clerk')->where('shop_id', $data['shop_id'])->where('user_id', $user['user_id'])
            ->find();

        if (isset($data['seatList'])) {
            if ($data['name'] == '') {
                $data['name'] = $data['seatList'][0]['name'];
            }

        }

        $c = new DayService();

        $date_arr = explode('-', $data['date']);

        $data['week']       = $c->get_week_day($data['date']);
        $data['order_no']   = OrderService::createOrderNo();
        $today              = $c->convertSolarToLunar($date_arr[0], $date_arr[1], $date_arr[2]);
        $data['lunar_date'] = $today[1] . $today[2];

        $data = array_merge($data, ['clerk_id' => $clerk['clerk_id'], 'shop_id' => $clerk['shop_id'],
            'store_id'                             => self::$storeId]);

        $data['order_status'] = 10;
        $data['is_send']      = $type;

        $data['pay_price']   = isset($data['seat_money']) ? $data['seat_money'] : 0;
        $data['total_price'] = isset($data['seat_money']) ? $data['seat_money'] : 0;
        $shopId              = $data['shop_id'];
        $shop                = Db::name('store_shop')->where('shop_id', $shopId)->find();

        $data['seat_money'] = $shop['seat_money'];

        $this->save($data);

        if (isset($data['liebianId'])) {
            //更新裂变用户
            Db::name('ding_shop_liebian')->where('mobile', $data['mobile'])->where('shop_id', $data['shop_id'])
                ->update(['status' => 1]);

        }

        if (isset($data['contentList'])) {
            // 内容
            OrderContentModel::increased((int) $this['id'], $data['contentList']);
        }
        if (! empty($data['mobile'])) {
            $clerkMember = new ClerkMemberModel;
            $clerkMember->add($data);
        }
        //更新用于预定次数
        Db::name('ding_clerk_member')->where('mobile', $data['mobile'])
            ->where('shop_id', $data['shop_id'])->inc('times', 1)->update();
        //餐位
        $data['order_id'] = $this['id'];

        OrderSeatModel::increased($data);

        //操作日记
        $log['content']  = '创建了此订单';
        $log['status']   = OrderTypeEnum::CREATE;
        $log['order_id'] = $this['id'];
        $log['clerk_id'] = $clerk['clerk_id'];
        $log['shop_id']  = $clerk['shop_id'];

        OrderLogModel::increased($log);

        $orderId = $this['id'];

        $clerks = Db::name('store_shop_clerk')->where('shop_id', $clerk['shop_id'])
            ->group('user_id')
            ->where('reserve_msg', 1)
            ->select()->toArray();

        foreach ($clerks as $key => $value) {
            $opend_id = $value['oauth_id'];
            if ($opend_id) {
                // 执行发送

                $MessageService         = new MessageService;
                $content['template_id'] = 'yWrzJ1FuLCamRw_Rm55kwvtylWYD0JGys1U7g4_fMmk';
                $content['page']        = 'pagesNew/order/detail?orderId=' . $orderId . '&shopId=' . $shopId;

                $content['data']['thing4']            = $shop['shop_name'];
                $content['data']['time3']             = $data['date'] . ' ' . $data['time'];
                $content['data']['character_string5'] = $data['order_no'];
                $content['data']['thing6']            = $data['name'];
                $content['data']['const1']            = '订座成功';
                $content['data']['time4']             = $data['date'] . ' ' . $data['time'];
                //暂时注释
                $MessageService->send($opend_id, $content);

            }
        }

        //发送短信
        if ($type == 1) {
            $messageService = new OrderSendService(self::$storeId);
            $sex            = '先生/女士';
            if ($data['sex'] == 1) {
                $sex = '先生';
            } elseif ($data['sex'] == 2) {
                $sex = '女士';
            }
            // 获取当前小程序信息
            $config = self::getMpWxConfig();
            // 微信登录 (获取session_key)
            $WxUser = new Link($config['app_id'], $config['app_secret']);

            $param['path']  = 'pagesNew/order/detail';
            $param['query'] = 'orderId=' . $this['id'] . '&shopId=' . $clerk['shop_id'];

            $result = $WxUser->getLinkLong($param);
            $url    = $result['url_link'];

            $date          = $data['date'] . ' ' . $data['time'];
            $send['users'] = [['real_name' => $data['real_name'] . $sex, 'mobile' => $data['mobile'], 'date' => $date, 'seat_name' => $data['name'], 'page' => $url]];
            $send['clerk'] = $clerk;
            $send['shop']  = $shop;

            $messageService->send($send);
        }

        return $this['id'];

    }
    private static function getMpWxConfig(): array
    {
        $wxConfig = WxappSettingModel::getWxappConfig();
        if (empty($wxConfig['app_id']) || empty($wxConfig['app_secret'])) {
            throwError('请到后台小程序设置填写AppID和AppSecret参数');
        }
        return $wxConfig;
    }
    public function getListAll($shopId, $param)
    {
        $params = $this->setQueryDefaultValue($param, [

            'type'       => -1,
            'categoryId' => -1,
            'date'       => '',
        ]);
        // 检索查询条件
        $filter = [];

        $params['categoryId'] > 0 && $filter[] = ['category_id', '=', $params['categoryId']];
        $params['type'] > 0 && $filter[]       = ['type', '=', $params['type']];

        //今日动态
        if (! empty($params['date'])) {

            $time     = strtotime(Date('Y-m-d'));
            $filter[] = ['create_time', '>=', $time];
        }

        // 获取列表数据
        return $this->with(['clerk', 'letters', 'shop.logoImage'])

            ->where($filter)

            ->where('shop_id', '=', $shopId)
            ->where('is_delete', '=', 0)
            ->order(['create_time' => 'desc'])
            ->select()->toArray();
    }
    public function getList($shopId, $param)
    {
        $params = $this->setQueryDefaultValue($param, [
            'keyword'    => '',
            'type'       => -1,
            'categoryId' => -1,
        ]);
        // 检索查询条件
        $filter = [];

        $params['categoryId'] > 0 && $filter[]  = ['category_id', '=', $params['categoryId']];
        $params['type'] > 0 && $filter[]        = ['type', '=', $params['type']];
        ! empty($params['keyword']) && $filter[] = ['mobile', '=', $params['keyword']];
        //!empty($params['date']) && $filter[] = ['date', '=', $params['date']];
        // 获取列表数据
        return $this->with(['clerk', 'letters', 'shop.logoImage', 'seats'])

            ->where($filter)
            ->where('shop_id', $shopId)
            ->where('clerk_id', '>', 0)

            ->where('is_delete', '=', 0)
            ->order(['create_time' => 'desc'])
            ->paginate(15);
    }
    /*
		*用户订单
	*/
    public function getListUser($status)
    {
        // 获取当前用户ID
        $userId = UserService::getCurrentLoginUserId();
        // 检索查询条件
        $filter = [];

        if ($status == 1) {
            //待付款
            $filter[] = ['pay_status', '=', 10];
            $filter[] = ['order_status', '=', 10];

        }
        if ($status == 2) {
            //待确认
            $filter[] = ['order_status', '=', 0];

        }
        if ($status == 3) {
            //待使用
            $filter[] = ['order_status', '=', 10];

        }
        if ($status == 4) {
            //退款，售后，取消
            $filter[] = ['order_status', '=', 30];

        }

        // 获取列表数据
        return $this->with(['shop', 'seats.seat.image'])

            ->where($filter)

            ->where('is_delete', '=', 0)
            ->where('user_id', '=', $userId)
            ->order(['create_time' => 'desc'])
            ->paginate(15);
    }

    /*
		*用户订单-员工查看
	*/
    public function getListYuding($status, $shopId)
    {
        // 获取当前用户ID
        $userId = UserService::getCurrentLoginUserId();
        $clerk  = Db::name('store_shop_clerk')->where('user_id', $userId)->where('shop_id', $shopId)->where('is_delete', 0)->find();

        // 检索查询条件
        $filter = [];

        if ($status == 10) {
            //待确认
            $filter[] = ['order_status', '=', 0];

        }
        if ($status == 20) {
            //已确认
            $filter[] = ['order_status', '=', 10];

        }
        if ($status == 30) {
            //已取消
            $filter[] = ['order_status', '=', 30];

        }
        if ($status == 40) {
            //预订失败
            $filter[] = ['order_status', '=', 50];

        }
        $filter[] = ['clerk_id', 'in', [0, $clerk['clerk_id']]];
        // 获取列表数据
        return $this->with(['seats.seat'])

            ->where($filter)
            ->where('shop_id', $shopId)
            ->where('is_delete', '=', 0)
            ->where('source', '=', 2) //用户添加
            ->order(['create_time' => 'asc'])
            ->paginate(15);
    }

    /**
     * 订单支付事件
     * @param int $payType
     * @return bool
     */
    public function onPay(int $payType = OrderPayTypeEnum::WECHAT): bool
    {
        // 判断订单状态
        // $orderSource = OrderSourceFactory::getFactory($this['order_source']);
        // if (!$orderSource->checkOrderStatusOnPay($this)) {
        // 	$this->error = $orderSource->getError();
        // 	return false;
        // }

        // 余额支付
        if ($payType == OrderPayTypeEnum::BALANCE) {
            return $this->onPaymentByBalance($this['order_no']);
        }
        return true;
    }

    /**
     * 余额支付标记订单已支付
     * @param string $orderNo 订单号
     * @return bool
     */
    public function onPaymentByBalance(string $orderNo): bool
    {
        // 获取订单详情
        $service = new OrderPaySuccesService($orderNo);

        // 发起余额支付
        $status = $service->onPaySuccess(OrderPayTypeEnum::BALANCE);

        if (! $status) {
            $this->error = $service->getError();
        }
        return $status;
    }

    /**
     * 构建支付请求的参数
     * @param self $order 订单信息
     * @param int $payType 订单支付方式
     * @return array
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function onOrderPayment(self $order, int $payType): array
    {
        if ($payType == OrderPayTypeEnum::WECHAT) {
            return $this->onPaymentByWechat($order);
        }
        return [];
    }

    /**
     * 构建微信支付请求
     * @param self $order 订单详情
     * @return array
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function onPaymentByWechat(self $order): array
    {
        return PaymentService::wechat(
            $order['order_id'],
            $order['order_no'],
            $order['pay_price'],
            10
        );
    }
}
